package com.hupu.jrs.ui.pmlist

import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.hupu.jrs.R
import com.hupu.jrs.bean.Pm
import com.hupu.jrs.widget.LabelCardView

/**
 * Created by sll on 2016/5/6.
 */
class PmListAdapter @Inject
constructor() : RecyclerView.Adapter<PmListAdapter.ViewHolder>() {

    private var pms: List<Pm> = ArrayList<Pm>()
    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    interface OnItemClickListener {
        fun onPmListClick(pm: Pm?)
    }

    fun bind(pms: List<Pm>) {
        this.pms = pms
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
                LayoutInflater.from(parent.context).inflate(R.layout.item_list_pm, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val pm = pms[position]
        holder.mPm = pm
        if (!TextUtils.isEmpty(pm.header)) {
            holder.ivIcon!!.setImageURI(Uri.parse(pm.header))
        }
        holder.tvContent!!.setText(pm.content)
        holder.tvName!!.setText(pm.nickname)
        val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
        val date = Date(java.lang.Long.valueOf(pm.last_time) * 1000)
        holder.tvTime!!.text = format.format(date)
        if (!TextUtils.isEmpty(pm.unread) && pm.unread.equals("1")) {
            holder.cardView!!.setLabelText("NEW")
            holder.cardView!!.setLabelVisual(true)
        } else {
            holder.cardView!!.setLabelVisual(false)
        }
    }

    override fun getItemCount(): Int {
        return pms.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var mPm: Pm? = null

        @BindView(R.id.tvName)
        var tvName: TextView? = null
        @BindView(R.id.tvContent)
        var tvContent: TextView? = null
        @BindView(R.id.tvTime)
        var tvTime: TextView? = null
        @BindView(R.id.ivIcon)
        var ivIcon: SimpleDraweeView? = null
        @BindView(R.id.listItem)
        var cardView: LabelCardView? = null

        @OnClick(R.id.listItem)
        fun listItemClick() {
            if (onItemClickListener != null) {
                onItemClickListener!!.onPmListClick(mPm)
            }
        }

        init {
            ButterKnife.bind(this, itemView)
        }
    }
}
